package huffman;

import huffman.HuffmanIn.Item;
import huffman.HuffmanIn.Node;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeMap;

public class HuffmanOut extends DataInputStreamEx {
	private HuffmanHeader header;
	private FileOutputStream fos;
	public HuffmanOut(String in) throws IOException {
		super(new FileInputStream(in));
//		FileInputStream fis = news FileInputStream(in);
		header = HuffmanHeader.readFromCompressedFile(this);
		
//		System.out.println(getChannel().position() + " " + this.available());
	}

	public void uncompressTo(String file) throws IOException {
		try {
			fos = new FileOutputStream(file);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Byte b = null;
		String currentsearch = "";
		
		TreeMap<String, Byte> l = new TreeMap<String, Byte>();
		for(Item it: header.items) {
			if(it != null && it.character 
					!= null) {
				l.put(it.value, it.character);
			}
		}

		while(this.available() > 0) {
			if(readBit()) {
				currentsearch += "1";
			} else {
				currentsearch += "0";
			}
			b = l.get(currentsearch);
			if(b != null) {
				fos.write(b);
				currentsearch = "";
				b = null;
			} 
		}
		fos.close();
//		fos.flush();
	}

}
